
using UnityEngine;
using UnityEngine.EventSystems;

public static class HvoUtils
{
    public static Vector2 InputPosition => Input.touchCount > 0 ? Input.GetTouch(0).position : Input.mousePosition;
    public static bool IsLeftClickOrTapDown => Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began);//0代表鼠标左键，1代表右键，2代表中键,或者触摸了
    public static bool IsLeftClickOrTapup => Input.GetMouseButtonUp(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended);

    private static Vector2 m_InitialTouchPosition; // 初始触摸位置

    public static bool TryGetShortClickPosition(out Vector2 inputPosition, float maxDistance = 5f)
    {   
        inputPosition = InputPosition;
        // 触摸就获取触摸位置，否则鼠标位置
        // Debug.Log(inputPosition);
        if (IsLeftClickOrTapDown)
        {
            m_InitialTouchPosition = inputPosition;
        }

        if (IsLeftClickOrTapup)//0代表鼠标左键，1代表右键，2代表中键,或者触摸了
        {
            if (Vector2.Distance(m_InitialTouchPosition, inputPosition) < maxDistance)
            {
                return true;
            }
        }

        return false;
    }

    public static bool TryGetHoldPosition(out Vector3 worldPosition)
    {
        if (Input.touchCount > 0)
        {   
            worldPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            return true;
        }
        else if (Input.GetMouseButton(0))
        {
            worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            return true;
        }

        worldPosition = Vector3.zero;
        return false;
    }

    public static bool IsPointerOverUIElement() // 解决鼠标点击动作栏也会触发移动的问题
    {
        if (Input.touchCount > 0)
        {
            var touch = Input.GetTouch(0);
            return EventSystem.current.IsPointerOverGameObject(touch.fingerId); // 检查触摸是否悬停在UI元素上
        }
        else
        {
            return EventSystem.current.IsPointerOverGameObject(); // 检查鼠标是否悬停在UI元素上
        }
    }

}